package com.rockbb.common.utilities;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

public class ObjectUtils {

	private static Logger logger = Logger.getLogger(ObjectUtils.class);

	public static Object getClassInstanceByName(String className) 
	{
		Object obj = null;
		try 
		{
			obj = (Class.forName(className).getClassLoader().loadClass(className)).newInstance();
		} 
		catch (ClassNotFoundException e) 
		{
			logger.info("ClassNotFoundException");
			logger.debug("Exception details:", e);
		} 
		catch (InstantiationException e) 
		{
			logger.info("InstantiationException");
			logger.debug("Exception details:", e);
		} 
		catch (IllegalAccessException e) 
		{
			logger.info("IllegalAccessException");
			logger.debug("Exception details:", e);
		} 
		catch (Exception e) 
		{
			logger.info("Unknown Exception");
			logger.debug("Exception details:", e);
		}
		return obj;
	}

	public static <T> Map<String, List<String>> compare(T a, T b, Class<T> t) 
	{
		Map<String, List<String>> diff = new HashMap<String, List<String>>();

		Field[] fields =  t.getDeclaredFields();
		if (fields != null)
		{
			for (Field field : fields) 
			{
				try
				{
					field.setAccessible(true);
					Object property1 = field.get(a);
					Object property2 = field.get(b);
					if (property1 == null && property2 == null)
					{
						// Do nothing
					}
					else if (property1 == null && property2 != null)
					{
						diff.put(field.getName(), Arrays.asList("null", property2.toString()));
					}
					else if (property2 == null && property1 != null)
					{
						diff.put(field.getName(), Arrays.asList(property1.toString(), "null"));
					}
					else if (!property1.equals(property2)) 
					{
						diff.put(field.getName(), Arrays.asList(property1.toString(), property2.toString()));
					}
				}
				catch (IllegalAccessException e)
				{
					logger.info("IllegalAccessException");
					logger.debug("IllegalAccessException details:", e);
				}
				catch (Exception e) 
				{
					logger.info("Unknown Exception");
					logger.debug("Exception details:", e);
				}
				finally
				{
					field.setAccessible(false);
				}
			}
		}
		
		return diff;
	}

}
